import 'dart:async';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:zhibao_flutter/api/user/user_view_model.dart';
import 'package:zhibao_flutter/pages/login/login_view.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/config/app_config.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/my_theme.dart';
import 'package:zhibao_flutter/util/my_theme.dart';
import 'package:zhibao_flutter/util/ui/my_toast.dart';
import 'package:zhibao_flutter/widget/bt/login_ink_well.dart';
import 'package:get/get.dart';

/*
* mobilePhone String 手机号/邮箱
* isSend bool 是否初始化发送
* type int 0=获取验证码 可用；1=重新获取 禁用；2=重新获取 可用 ;
* sence 场景:login登录，register注册，forgetPassword忘记密码,withdraw提现,
* transfer转账，
* payPassword支付密码,cancellation注销
*/
class GetCodeBt extends StatefulWidget {
  final TextEditingController mobilePhone;
  final bool isSend;
  final String sence;
  final FocusNode codeFocusNode;
  final LoginType loginType;

  GetCodeBt({
    required this.mobilePhone,
    this.isSend = false,
    required this.sence,
    // 注册登录-点击获取验证码后，光标应定位至验证码输入框，注销账号时同样有此问题
    required this.codeFocusNode,

    /// 注册时必须传递，其他情况不需要，因为已经是完整的账号了。
    required this.loginType,
  });

  @override
  _GetCodeBtState createState() => _GetCodeBtState();
}

class _GetCodeBtState extends State<GetCodeBt>
    with AutomaticKeepAliveClientMixin {
  int type = 0;
  Timer? timer;
  int remainingTime = 60;

  @override
  void initState() {
    super.initState();
    if (widget.isSend && strNoEmpty(widget.mobilePhone.text)) {
      firstSend();
    }
  }

  void count() {
    if (timer != null) return;
    timer = Timer.periodic(Duration(seconds: 1), (_timer) {
      if (remainingTime > 0) {
        remainingTime--;
      } else {
        type = 2;
        timer?.cancel();
        timer = null;
      }
      if (mounted) setState(() {});
    });
  }

  Future start({VoidCallback? onSendSuccess}) async {
    final head =
        widget.loginType == LoginType.phone ? AppConfig.countyCodeGet : "";
    final value = await userViewModel.sendCodeLogin(context,
        account: head + widget.mobilePhone.text,
        type: widget.sence == "register" || widget.sence == "forgetPassword"
            ? 0

            /// payPassword 支付密码，也就是1
            : widget.sence == "payPassword"
                ? 1
                : widget.sence == "withdraw"
                    ?
                    // withdraw提现就是2
                    2

                    /// transfer转账填3
                    : widget.sence == "transfer"
                        ? 3
                        : 0);
    widget.codeFocusNode.requestFocus();
    if (value.data == null) {
      return;
    }
    if (onSendSuccess != null) onSendSuccess();
    if (type == 2) {
      type = 1;
    }
    remainingTime = 60;
    count();
    setState(() {});
  }

  void firstSend() {
    start(onSendSuccess: () {
      type = 1;
    });
  }

  void handle() {
    if (type == 1) {
      return;
    }

    if (!strNoEmpty(widget.mobilePhone.text)) {
      myFailToast('enterPhoneEmail'.tr);
      // } else if (!isMobilePhoneNumber(widget.mobilePhone.value)) {
      //   myFailToast('请输入正确手机号/邮箱');
    } else if (type == 0) {
      firstSend();
    } else {
      start();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final content = Container(
      padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 12.0),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(14.0)),
      child: ValueListenableBuilder(
        valueListenable: widget.mobilePhone,
        builder: (context, TextEditingValue value, child) {
          return Text(
            () {
              return type == 1
                  ? '${'ResendInSeconds'.tr}${remainingTime}s'
                  : type == 2
                      ? 'Resend'.tr
                      : 'GetVerificationCode'.tr;
            }(),
            style: TextStyle(
              fontSize: 14.0,
              color: Color(!strNoEmpty(value.text) || type == 1
                  ? 0xff999999
                  : 0xff61605F),
            ),
          );
        },
      ),
    );
    // Tower 任务: 注册登录-输入手机号/邮箱后点击’获取验证码’时提示’请先阅读且同意协议’，协议勾选的判断应后置到点击登录时 ( https://tower.im/teams/995083/todos/737 )
    return InkWell(child: content, onTap: handle);
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
    timer = null;
  }

  @override
  bool get wantKeepAlive => true;
}
